package top.dimples.aspectj;

import cn.hutool.core.util.ArrayUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.dimples.anotation.Permission;
import top.dimples.common.ApiResponse;
import top.dimples.common.Consts;
import top.dimples.common.Status;
import top.dimples.service.RoleService;
import top.dimples.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * <p>
 * 使用 aop 切面检查用户
 * </p>
 */
@Aspect
@Component
@Slf4j
public class AopPermission {

    @Autowired
    private RoleService roleService;


    /**
     * 切入点
     */
    @Pointcut("@annotation(top.dimples.anotation.Permission)")
    public void permission() {

    }

    /**
     * 环绕操作
     *
     * @param point 切入点
     * @return 原方法返回值
     * @throws Throwable 异常信息
     */
    @Around("permission()")
    public Object aroundPermission(ProceedingJoinPoint point) throws Throwable {

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Permission annotation = method.getAnnotation(Permission.class);
        String[] permission = annotation.value();
        if (ArrayUtil.isNotEmpty(permission) && checkPermission(permission)) {
            return point.proceed();
        }
        return ApiResponse.ofStatus(Status.ACCESS_DENIED);
    }

    /**
     * 权限检查
     *
     * @return 检查当前用户是否有该角色
     */
    private Boolean checkPermission(String[] permission) throws IOException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String Token = request.getHeader(Consts.AUTHORIZATION);
        HashMap<String, String> tokenMap = JwtUtil.parseToken(Token);
        String[] roles = tokenMap.get("roles").split(",");
        // 判断是否有 admin（超级管理员） 角色
        if(ArrayUtil.containsIgnoreCase(roles,"admin")){
            return true;
        }
        return ArrayUtil.containsAny(permission,roles);
    }


}
